﻿Namespace FileSystemScan
    Friend Class Handler_GroupIndenticalFilenames
        Friend Shared Sub Scan(ByVal share As Entities.Share, ByVal rootPath As String)
            Handler_ScanFolder.Scan(share, AddressOf GroupFilesToItemCandidates, AddressOf GetKeyForItem, rootPath)
        End Sub

        Private Shared Function GroupFilesToItemCandidates(ByVal share As Entities.Share, ByVal files As Generic.List(Of IO.FileInfo)) As Generic.Dictionary(Of String, Handler_ScanFolder.ItemCandidate)
            Dim aRet As New Generic.Dictionary(Of String, Handler_ScanFolder.ItemCandidate)
            For Each clsFI As IO.FileInfo In files
                Dim clsItemSig As Handler_ScanFolder.ItemCandidate = GetItemCandidateNameByFilePath(clsFI.Name)
                If aRet.ContainsKey(clsItemSig.Key) Then
                    clsItemSig = aRet.Item(clsItemSig.Key)
                Else
                    aRet.Add(clsItemSig.Key, clsItemSig)
                End If
                clsItemSig.AddFile(clsFI)
            Next
            Return aRet
        End Function
        Private Shared Function GetKeyForItem(ByVal share As Entities.Share, ByVal item As Entities.SharedItem) As String
            Return item.Name.ToLower
            'Return System.IO.Path.Combine(item.RelativeDirectory, item.Name.ToLower)
        End Function

        Private Shared Function GetItemCandidateNameByFilePath(ByVal filePath As String) As Handler_ScanFolder.ItemCandidate
            Dim clsRet As New Handler_ScanFolder.ItemCandidate
            'remove everything but the actual filename
            Dim strFileName As String = System.IO.Path.GetFileNameWithoutExtension(filePath)

            With Framework.IO.Utils.CleanUpFilename(strFileName)
                strFileName = .Name
                clsRet.Comment = .Comment
            End With

            'now, if filename without extension ends with a dot and a two letter language code, remove it
            If strFileName.Length > 3 AndAlso strFileName.Chars(strFileName.Length - 3) = "." Then
                strFileName = strFileName.Substring(0, strFileName.Length - 3).Trim
            End If
            clsRet.Name = strFileName.Replace("."c, " ").Trim
            clsRet.Key = strFileName.ToLower
            Return clsRet
        End Function
    End Class
End Namespace